package smartq.app;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;

import smartq.DB.BookQ;
import smartq.DB.Table;
import smartq.DB.Connect;
import smartq.general.DateTime;

import com.app.smart_q.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


public class SmartQ_ShowDetail_Activity extends Activity {
	
	static final int TIME_DIALOG_ID = 1111;
    private TextView output;
    public Button btnClick;
 
    private int hour;
    private int minute;
    
	private String SessionUsrOID = "Application";
	
	Connect con = new Connect(); 
	ResultSet rs;
	String SexS;
	String  OID,
		UsrOpt,
		IsActive,
		IsDeleted,
		CustomerPhonenumber,
		CustomerFirstName,
		CustomerLastName,
		CustomerSex,
		CustomerClass,
		CustomerShop,
		CustomerFood,
		CustomerTime,
		CustomerAlet,
		CustomerTable,
		CustomerNumber,
		CustomerStartTime,
		CustomerEndTime,
		CustomerQ,
		CustomerStatus,
		CustomerIsMessage,
		CustomerWaittime;
	
	myDBClass myDb = new myDBClass(this);
	
	ArrayList<String> SpinnerShop= new ArrayList<String>();
	ArrayList<String> SpinnerTable= new ArrayList<String>();
	ArrayList<String> SpinnerAlert= new ArrayList<String>();
	ArrayList<String> SpinnerTimeAlert= new ArrayList<String>();
	ArrayList<String> SpinnerFood= new ArrayList<String>();
	ArrayList<String> SpinnerNumber= new ArrayList<String>();
	
	
	//-------GET_SET-----------------------------------//
	public String getOID() {
		return OID;
	}

	public void setOID(String oID) {
		OID = oID;
	}

	@SuppressWarnings("static-access")
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.smartq_showdetail);
		
		output = (TextView) findViewById(R.id.editText_TimeNow);
		
		 Bundle bundle = getIntent().getExtras();
		 CustomerPhonenumber = ((String) bundle.get("CustomerPhonenumber"));
		 
		BookQ usr = new BookQ();
		DateTime dt = new DateTime();
		String DateNow =dt.getDateNowymd();
			
		 try {
				rs = usr.selectBookQ(CustomerPhonenumber,"1", DateNow,"","Waiting");
				if (rs.next()) {
					setOID(rs.getString("OID"));
					CustomerFirstName = rs.getString("CustomerFirstName");
					CustomerLastName = rs.getString("CustomerLastName");
					CustomerSex = rs.getString("CustomerSex");
					CustomerClass = rs.getString("CustomerClass");
					CustomerShop = rs.getString("CustomerShop");
					CustomerFood = rs.getString("CustomerFood");
					CustomerTime = rs.getString("CustomerTime");
					CustomerAlet = rs.getString("CustomerAlet");
					CustomerTable = rs.getString("CustomerTable");
					CustomerNumber = rs.getString("CustomerNumber");
					CustomerIsMessage = rs.getString("CustomerIsMessage");
				}else{
					
				}
			}catch (Exception e) {
                finish();
			}
		 
		 
	        
	     
		 TimeAlert(CustomerTime);
		 Shop();
		 Table();
		 Number();
		 Alert();
		 Food();
		
		// Watch for button clicks.
        Button button = (Button)findViewById(R.id.smartq_insertQ);
        button.setOnClickListener(buttonInsert);
        
        button = (Button)findViewById(R.id.smartq_cancle);
        button.setOnClickListener(buttonCancle);
 
        
        
        /********* display current time on screen Start ********/
        
	     final Calendar c = Calendar.getInstance();
	     // Current Hour
	     hour = c.get(Calendar.HOUR_OF_DAY);
	    // Current Minute
	     minute = c.get(Calendar.MINUTE);
	         
	    // set current time into output textview
	     //updateTime(hour, minute);
	     output.setText(CustomerTime);
	         
	    /********* display current time on screen End ********/
	         
	     // Add Button Click Listener
	     addButtonClickListener();    
	     
	}
	
	@SuppressWarnings("static-access")
	public boolean CheckForm(){
		if(CustomerIsMessage.equals("##### เเจ้งเตือน  #####")){
			Toast.makeText(SmartQ_ShowDetail_Activity.this,String.valueOf("ข้อมูล แจ้งเตือน ไม่ถูกต้อง \nกรุณาตรวจสอบข้อมูลอีกครั้งค่ะ"),Toast.LENGTH_SHORT).show();
			return false;
			
		}
		if(CustomerShop.equals("##### เลือกร้าน  #####")){
			Toast.makeText(SmartQ_ShowDetail_Activity.this,String.valueOf("ข้อมูล ร้านค้า ไม่ถูกต้อง \nกรุณาตรวจสอบข้อมูลอีกครั้งค่ะ"),Toast.LENGTH_SHORT).show();
			return false;
		}
		if(CustomerAlet.equals("##### เลือกการเเจ้งเตือน  #####")){
			Toast.makeText(SmartQ_ShowDetail_Activity.this,String.valueOf("ข้อมูล การเเจ้งเตือน ไม่ถูกต้อง\nกรุณาตรวจสอบข้อมูลอีกครั้งค่ะ"),Toast.LENGTH_SHORT).show();
			return false;
		}
		if(CustomerTable.equals("##### เลือกโต๊ะ  #####")){
			Toast.makeText(SmartQ_ShowDetail_Activity.this,String.valueOf("ข้อมูล โต๊ะ ไม่ถูกต้อง \nกรุณาตรวจสอบข้อมูลอีกครั้งค่ะ"),Toast.LENGTH_SHORT).show();
			return false;
		}else{
			DateTime dt = new DateTime();
			String DateNow =dt.getDateNowymd();
			BookQ usr = new BookQ();
			String tnn = dt.getTimeNow();
			String tuu = output.getText().toString();
			int TNN=dt.convertTime(tnn);
			int TUU=dt.convertTime(tuu);
			
			rs = null;
			try {
				rs = usr.selectBookQ("","1",DateNow,CustomerTable,"Waiting");
				while (rs.next()) {
					if((TUU-TNN)<10 && !CustomerTable.equals(rs.getString("CustomerTable"))){
						Toast.makeText(SmartQ_ShowDetail_Activity.this,String.valueOf("โต๊ะที่เลือกในช่วงเวลาดังกล่าว ไม่ว่าง \nกรุณาตรวจสอบข้อมูลอีกครั้งค่ะ"),Toast.LENGTH_SHORT).show();
						return false;
					}
					String timeCheck = rs.getString("CustomerTime");
					String TimeUse = output.getText().toString();
					int TC=dt.convertTime(timeCheck);
					int TU=dt.convertTime(TimeUse);
					if((TC-TU)<59){
						Toast.makeText(SmartQ_ShowDetail_Activity.this,
								String.valueOf("ขณะนี้โต๊ะไม่ว่าง. \n กรุณาตรวจสอบเวลาอีกครั้งค่ะ."),
								Toast.LENGTH_SHORT).show();
						return false;
					}
				}
			} catch (Exception e) {
				return false;
			} 
			
			
			
			Table usr2 = new Table();
			ResultSet rs2 = null;
			try {
				rs2 = usr2.selectTable(CustomerTable);
				while (rs2.next() && !rs2.getString("TableName").equals(CustomerTable)) {
					//System.out.println("wqewqewqewqeqwe");
					String timeCheck = rs2.getString("TableTime");
					String TimeUse = output.getText().toString();
					int TC=dt.convertTime(timeCheck);
					int TU=dt.convertTime(TimeUse);
					if((TC-TU)<10){
						Toast.makeText(SmartQ_ShowDetail_Activity.this,
								String.valueOf("ขณะนี้โต๊ะไม่ว่าง\n กรุณาตรวจสอบเวลาอีกครั้งค่ะ."),
								Toast.LENGTH_SHORT).show();
						return false;
					}
				}
			} catch (Exception e) {
			} 
			
		}
		return true;
	}
    
	private OnClickListener buttonInsert = new OnClickListener() {
        public void onClick(View v) {
			rs = null;
			if(CheckForm()){
				BookQ usr = new BookQ(
						getOID(),
						SessionUsrOID, 
						"1", 
						null, 
						CustomerPhonenumber,
						CustomerFirstName, 
						CustomerLastName,
						CustomerSex, 
						CustomerClass,
						
						CustomerShop,
						CustomerFood,
						output.getText().toString(),
						CustomerAlet,
						CustomerTable,
						CustomerNumber,
						"-",
						"-",
						"-",
						"Waiting",
						CustomerIsMessage,
						"-"
						);

				try {
					if (usr.OperationData("Update") != null) {
						Intent newActivity = new Intent(getApplicationContext(),SmartQ_Tap_Main.class);	                          
                        newActivity.putExtra("CustomerPhonenumber", CustomerPhonenumber);
                        startActivity(newActivity);
                        finish();
					} 
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
            
    }; 
    
    private OnClickListener buttonCancle = new OnClickListener() {
        public void onClick(View v) {
        	onBackPressed();
        }
    }; 
	
	@SuppressWarnings("static-access")
	private void TimeAlert(String tcc) {
		SpinnerTimeAlert.clear();
		final Spinner TimeAlert = (Spinner) findViewById(R.id.Spinner_timeAlert);
		SpinnerTimeAlert.add(CustomerIsMessage);
		
		DateTime dt = new DateTime();
		String TN = dt.getTimeNow();
		int tnn=dt.convertTime(TN);
		int tuu=dt.convertTime(tcc);
		int TR = tuu-tnn;
		if(TR>60){
			TR =60;
		}
		for(int j=5;j<=TR;j+=5){
			SpinnerTimeAlert.add("ล่วงหน้า "+j+" นาที");
		}
			
				ArrayAdapter<String> empolyeeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,SpinnerTimeAlert);
				empolyeeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
				TimeAlert.setAdapter(empolyeeAdapter);
				
				TimeAlert.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() { 

		            public void onItemSelected(AdapterView<?> adapterView, 
		          	View view, int i, long l) { 
		            	CustomerIsMessage = SpinnerTimeAlert.get(i);
		            }
		            public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
	    				Toast.makeText(SmartQ_ShowDetail_Activity.this,
	             				String.valueOf("Your Selected Empty"),
	             					Toast.LENGTH_SHORT).show();
					} 

	      });
	}
	
	private void Shop() {
		final Spinner SpShop = (Spinner) findViewById(R.id.spinner_showq_shop);
		 rs = con.selectData("SELECT * FROM  Shops WHERE IsDeleted= '0' ");	
		
		 SpinnerShop.add(CustomerShop);	
				try {
					while(rs.next()){          
						SpinnerShop.add(rs.getString("ShopName"));
						}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}      
			
				ArrayAdapter<String> empolyeeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,SpinnerShop);
				empolyeeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
				SpShop.setAdapter(empolyeeAdapter);
				
				SpShop.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() { 

		            public void onItemSelected(AdapterView<?> adapterView, 
		          	View view, int i, long l) { 
		            	CustomerShop = SpinnerShop.get(i);
		            	}
		            public void onNothingSelected(AdapterView<?> arg0) {
	    				Toast.makeText(SmartQ_ShowDetail_Activity.this,
	             				String.valueOf("Your Selected Empty"),
	             					Toast.LENGTH_SHORT).show();
					} 

	      });
	}
	
	private void Table() {
		final Spinner SpTable = (Spinner) findViewById(R.id.Spinner_table);
		 rs = con.selectData("SELECT * FROM  [dbo].[Table] WHERE IsDeleted= '0' ");		
		
		 SpinnerTable.add(CustomerTable);	
				try {
					while(rs.next()){          
						SpinnerTable.add(rs.getString("TableName"));
						}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}      
			
				ArrayAdapter<String> empolyeeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,SpinnerTable);
				empolyeeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
				SpTable.setAdapter(empolyeeAdapter);
				
				SpTable.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() { 

		            public void onItemSelected(AdapterView<?> adapterView, 
		          	View view, int i, long l) { 
		            	CustomerTable = SpinnerTable.get(i);
		            	}
		            public void onNothingSelected(AdapterView<?> arg0) {
	    				Toast.makeText(SmartQ_ShowDetail_Activity.this,
	             				String.valueOf("Your Selected Empty"),
	             					Toast.LENGTH_SHORT).show();
					} 

	      });
	}
	
	private void Alert() {
		final Spinner SpAlert = (Spinner) findViewById(R.id.spinner_showq_alert);  
		 
		 SpinnerAlert.add(CustomerAlet);	
		 SpinnerAlert.add("Application");
		 SpinnerAlert.add("SMS");
			
				ArrayAdapter<String> empolyeeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,SpinnerAlert);
				empolyeeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
				SpAlert.setAdapter(empolyeeAdapter);
				
				SpAlert.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() { 

		            public void onItemSelected(AdapterView<?> adapterView, 
		          	View view, int i, long l) { 
		            	CustomerAlet = SpinnerAlert.get(i);
		            	}
		            public void onNothingSelected(AdapterView<?> arg0) {
	    				Toast.makeText(SmartQ_ShowDetail_Activity.this,
	             				String.valueOf("Your Selected Empty"),
	             					Toast.LENGTH_SHORT).show();
					} 

	      });
	}
	
	private void Number() {
		final Spinner SpNumber = (Spinner) findViewById(R.id.insertq_numbers);  
		
		 SpinnerNumber.add(CustomerNumber);	
		 for(int i=1;i<7;i++){
			 SpinnerNumber.add(String.valueOf(i));
		 }
			
				ArrayAdapter<String> empolyeeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,SpinnerNumber);
				empolyeeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
				SpNumber.setAdapter(empolyeeAdapter);
				
				SpNumber.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() { 

		            public void onItemSelected(AdapterView<?> adapterView, 
		          	View view, int i, long l) { 
		            	CustomerNumber = SpinnerNumber.get(i);
		            	}
		            public void onNothingSelected(AdapterView<?> arg0) {
	    				Toast.makeText(SmartQ_ShowDetail_Activity.this,
	             				String.valueOf("Your Selected Empty"),
	             					Toast.LENGTH_SHORT).show();
					} 

	      });
	}
	
	private void Food() {
		final Spinner SpFood = (Spinner) findViewById(R.id.spinner_showq_foodmenu);
		if(CustomerClass.equals("Class A")){
			rs = con.selectData("SELECT * FROM  [dbo].[Foods] WHERE IsDeleted= '0' ");		   
			try {
				SpinnerFood.add(CustomerFood);	
				while(rs.next()){          
					SpinnerFood.add(rs.getString("FoodName"));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		}else{
			SpinnerFood.add("##### สำหรับ Class A #####");	
		}
				ArrayAdapter<String> empolyeeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,SpinnerFood);
				empolyeeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
				SpFood.setAdapter(empolyeeAdapter);
				
				SpFood.setOnItemSelectedListener(new  AdapterView.OnItemSelectedListener() { 

		            public void onItemSelected(AdapterView<?> adapterView, 
		          	View view, int i, long l) { 
		            	CustomerFood = SpinnerFood.get(i);
		            	}
		            public void onNothingSelected(AdapterView<?> arg0) {
	    				Toast.makeText(SmartQ_ShowDetail_Activity.this,
	             				String.valueOf("Your Selected Empty"),
	             					Toast.LENGTH_SHORT).show();
					} 

	      });
	}
	
	public void addButtonClickListener() {
		 
        btnClick = (Button) findViewById(R.id.buttom_time);
 
        btnClick.setOnClickListener(new OnClickListener() {
 
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(View v) {
 
                showDialog(TIME_DIALOG_ID);
 
            }
 
        });
 
    }
 
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
             
            // set time picker as current time
            return new TimePickerDialog(this, timePickerListener, hour, minute,
                    false);
 
        }
        return null;
    }
 
    private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
         
 
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
            // TODO Auto-generated method stub
            hour   = hourOfDay;
            minute = minutes;
 
            updateTime(hour,minute);
             
         }
 
    };
 
    @SuppressWarnings("unused")
	private static String utilTime(int value) {
         
        if (value < 10)
            return "0" + String.valueOf(value);
        else
            return String.valueOf(value);
    }
     
    // Used to convert 24hr format to 12hr format with AM/PM values
    private void updateTime(int hours, int mins) {
        String Ohours= String.valueOf(hours);
        String Omins= String.valueOf(mins);
//        String timeSet = "";
        if (mins < 10) {
        	Omins="0"+Omins;
        }
        if (hours < 10) {
        	Ohours="0"+Ohours;
        }
//            hours -= 12;
//            timeSet = "PM";
//        } else if (hours == 0) {
//            hours += 12;
//            timeSet = "AM";
//        } else if (hours == 12)
//            timeSet = "PM";
//        else
//            timeSet = "AM";
 
         
//        String minutes = "";
//        if (mins < 10)
//            minutes = "0" + mins;
//        else
//            minutes = String.valueOf(mins);
 
        // Append in a StringBuilder
//         String aTime = new StringBuilder().append(hours).append(':')
//                .append(minutes).append(" ").append(timeSet).toString();
         String aTime2 = Ohours+":"+Omins;
 
          output.setText(aTime2);
          TimeAlert(aTime2);
    }
    
	@Override
	public void onBackPressed() {
	  
	        new AlertDialog.Builder(this)
	        .setTitle("ย้อนกลับ")
	        .setMessage("ข้อมูลที่คุณได้แก้ไขจะไม่ถูกบันทึก \nคุณต้องการดำเนินการต่อหรือไม่")
	                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

	                    public void onClick(DialogInterface arg0, int arg1) {
	                        Intent newActivity = new Intent(getApplicationContext(),SmartQ_Tap_Main.class);	                          
	                        newActivity.putExtra("CustomerPhonenumber", CustomerPhonenumber);
	                        startActivity(newActivity);
	                        finish();
	                        overridePendingTransition(R.layout.fadeendout,R.layout.fadeendin);
	                    }
	                })
	                .setPositiveButton(android.R.string.no, null).create().show();
	    

	} 
}
